<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/1
 * Time: 17:07
 */

namespace app\order\service;


use app\course\model\CourseModel;
use app\classes\model\ClassModel;
use app\classes\model\ClassSeatModel;
use app\classes\model\ClassStudentModel;
use app\course\model\CourseCategoryModel;
use app\course\model\CoursesCartModel;
use app\financial\model\AwardCardModel;
use app\financial\model\DiscountModel;
use app\financial\model\HelpAwardModel;
use app\financial\model\OrderModel;
use app\portal\model\UserModel;
use app\student\model\StudentModel;
use app\system\model\SchoolModel;
use think\Db;
use think\Exception;

class OrderService
{

    /**
     * 订单表
     * @param $param
     */
    public function product_order($param)
    {
        $class_id = $param['class_id'];       //班级id
        $student_id = $param['student_id'];
        $discount_type = $param['discount_type'];  //获取优惠方式
        $cha_id = $param['cha_id'];  //获取优惠方式

        $course_model = new CourseModel(); //课程
        $user_model=new UserModel();
        $order_model = new OrderModel();  //order订单表
        $class_model = new ClassModel();  //班级表
        $award_model = new AwardCardModel(); //牛牛卡或者经学金卡
        $help_awrad = new HelpAwardModel();   //助学金
        $p_id = cmf_get_current_user_id(); //前台登录用户
        $class_seat_model = new ClassSeatModel(); //坐位表
        $class_student_model=new ClassStudentModel(); //class_student
        $student_model=new StudentModel();
        $balance=$user_model->where(['id'=>$p_id])->value('balance');
        if(empty($balance))
        {
            $balance=0;
        }

        //判断学生是否在此班级占座了
        $student_seat = $class_seat_model->where(['classes_id' => $class_id, 'student_id' => $student_id, 'delete_time' => 0])->find();

        //查看课时             //排课表
        $lesson_schema=Db::name('course_schedule')->where(['class_id'=>$class_id])->order('date','asc')->select();

        $lesson_schema = $lesson_schema->toArray(); //转化数据
        sortArrByField($lesson_schema,'date',$asc = true); //时间排序（防止加课）正序
        $last=count($lesson_schema); //取得最后一个课时日期



        $class_data=$class_model->where('id', $class_id)->find();//class
        $course_id = $class_data['course_id'];   //课程id
        $school_id = $class_data['school_id'];   //校区id
        $classroom_id = $class_data['classroom_id'];   //教室id


        $course_data = $course_model->where('id', $course_id)->find(); //course表
        $length = $course_data['course_hour'] ; //课时长度

        $data_class = $class_model->where(['id' => $class_id])->find(); //获取班级
        $data = []; //order
        $data_student=[];//class_student
        $data_seat=[];//class_seat
        $class_name=$class_data['name'];

        //插板过来的学生 ，算课时
        if (!empty($cha_id)) {
            $cur_time = time();
            foreach ($lesson_schema as $k => $v) { //找出课时
                if (!empty($lesson_schema[$k + 1]['date'])) { //一般都是存在的2课时以上的
                    if ($cur_time > $lesson_schema[$k]['date'] && $cur_time < $lesson_schema[$k + 1]['date']) {
                        $progress = $lesson_schema[$k]['schedule']; //当前课时
                        $progress_sheng = $length - $progress; //剩余课时
                    } elseif ($cur_time < $lesson_schema[0]['date']) { //小于开课时间
                        $progress = 0; //当前课时
                        $progress_sheng = $length - $progress; //剩余课时
                    } else if ($cur_time > $lesson_schema[$last - 1]['date']) {  //已经结课
                        $progress = $length; //当前课时
                        $progress_sheng = 0; //剩余课时
                    }
                }else{
                    if ($cur_time > $lesson_schema[$k]['date'] && $cur_time < $lesson_schema[$k + 1]['date']) {
                        $progress = $lesson_schema[$k]['schedule']; //当前课时
                        $progress_sheng = $length - $progress; //剩余课时
                    } elseif ($cur_time < $lesson_schema[0]['date']) { //小于开课时间
                        $progress = 0; //当前课时
                        $progress_sheng = $length - $progress; //剩余课时
                    } else if ($cur_time > $lesson_schema[$last - 1]['date']) {  //已经结课
                        $progress = $length; //当前课时
                        $progress_sheng = 0; //剩余课时
                    }
                }
            }
            if(isset($_SESSION['progress']))
            {
                unset($_SESSION['progress']);
            }
            $_SESSION['progress']=$progress_sheng; //class_student 总统计分析插板人数几课时,存如表状态
            $data_student['student_status'] = 3; //3.插班
            $data_student['progress']=$_SESSION['progress'];
        }
        else{ //不是插板过来的课时数
            $progress = $length; //当前课时
            $progress_sheng = 0; //剩余课时
            $data_student['student_status'] = 0;
        }
        if(isset($_SESSION['student_status']) && !empty($_SESSION['student_status']))
        {
            $data_student['student_status'] = 5; //预选班的报名
        }
        if(isset($_SESSION['student_status1']) && !empty($_SESSION['student_status1']))
        {
            $data_student['student_status'] = 4;//4:续班
        }
        //续班的原班级，统计分析用
        if(isset($_SESSION['class_id']) && !empty($_SESSION['class_id']))
        {
            $data_student['old_class_id'] = $_SESSION['class_id']; ///续班的原班级，统计分析用
        }


        $data_student['insert_class_time'] = time();
        $data_student['course_id'] = $course_id;
        $data_student['class_id'] = $class_id;
        $data_student['school_id'] = $school_id;
        $data_student['classroom_id'] = $classroom_id;
        $data_student['student_id'] = $student_id;


        $student_seat = serialize($param['student_seat']);
        $data_seat['student_seat']= $student_seat;
        $data_seat['classes_id']= $class_id;
        $data_seat['course_id']= $course_id;
        $data_seat['student_id']= $student_id;
        $data_seat['classroom_id'] = $classroom_id;
        $data_seat['create_time']= time();

        //

        $_SESSION['student_id']=$student_id;

        //连报方式
        $data_continue=[]; //连报的话，需要东西存上两个班级的信息或者两个班级的信息，在家校通中就没有了续班，因为续班续过了
        $enable_class=$this->enable_class($class_id);

        $year_money = 0; //算价格
        $data['continue_year_money'] = 0; //order中的字段continue_year_money，1，2,3
        if (isset($discount_type) && !empty($discount_type)) { //存在连报且不为空
            if ($discount_type == 1) { //一年连报
                $year_money = $course_model->where('id', $course_id)->value('one_reduce_price');
                $data['continue_year_type'] = 1;
                $data['continue_year_money'] = $course_data['total_price'] - $year_money;
            }
            //选择的连报二年的方式
            if ($discount_type == 2) {

                $class_name2=$class_model->where(['id'=>$enable_class[0]])->value('name');
                $class_name=$class_name.','.$class_name2.'连报';


                $year_money = $course_model->where('id', $course_id)->value('two_reduce_price');
                $year_one = $course_model->where('id', $course_id)->value('one_reduce_price');
                $data['continue_year_type'] = 2;
                $data['continue_year_money'] = $course_data['total_price'] * 2 - $year_money;
                $continue_class2=Db::name('class')->where(['id'=>$enable_class[0]])->find();
                $data_student2['insert_class_time'] = time();
                $data_student2['course_id'] =   $continue_class2['course_id'];
                $data_student2['class_id'] = $enable_class[0];
                $data_student2['school_id'] =  $continue_class2['school_id'];
                $data_student2['classroom_id'] = $continue_class2['classroom_id'];
                $data_student2['student_id'] = $student_id;
                $data_student2['student_status'] = 4;


                $student_seat = serialize($param['student_seat']);
                $data_seat2['student_seat']= $student_seat;
                $data_seat2['classes_id']= $enable_class[0];
                $data_seat2['course_id']=  $continue_class2['course_id'];
                $data_seat2['classroom_id'] = $continue_class2['classroom_id'];
                $data_seat2['student_id']= $student_id;
                $data_seat2['create_time']= time();

            }
            //选择的连报三年的方式
            if ($discount_type == 3) {

                $class_name2=$class_model->where(['id'=>$enable_class[0]])->value('name');
                $class_name3=$class_model->where(['id'=>$enable_class[1]])->value('name');

                $class_name=$class_name.','.$class_name2.',' .$class_name3.'连报';


                $year_money = $course_model->where('id', $course_id)->value('three_reduce_price');
                $year_one = $course_model->where('id', $course_id)->value('one_reduce_price');
                $year_two = $course_model->where('id', $course_id)->value('two_reduce_price');
                $data['continue_year_type'] = 3;
                $data['continue_year_money'] = $course_data['total_price'] * 3 - $year_money;

                $continue_class2=Db::name('class')->where(['id'=>$enable_class[0]])->find();
                $data_student2['insert_class_time'] = time();
                $data_student2['course_id'] =   $continue_class2['course_id'];
                $data_student2['class_id'] = $enable_class[0];
                $data_student2['school_id'] =  $continue_class2['school_id'];
                $data_student2['classroom_id'] = $continue_class2['classroom_id'];
                $data_student2['student_id'] = $student_id;
                $data_student2['student_status'] = 4;



                $student_seat = serialize($param['student_seat']);
                $data_seat2['student_seat']= $student_seat;
                $data_seat2['classes_id']= $enable_class[0];
                $data_seat2['course_id']=  $continue_class2['course_id'];
                $data_seat2['classroom_id'] = $continue_class2['classroom_id'];
                $data_seat2['student_id']= $student_id;
                $data_seat2['create_time']= time();




                $continue_class3=Db::name('class')->where(['id'=>$enable_class[1]])->find();
                $data_student3['insert_class_time'] = time();
                $data_student3['course_id'] = $continue_class3['course_id'];
                $data_student3['class_id'] = $enable_class[1];
                $data_student3['school_id'] = $continue_class3['school_id'];
                $data_student3['classroom_id'] =$continue_class3['classroom_id'];
                $data_student3['student_id'] = $student_id;
                $data_student3['student_status'] = 4;



                $student_seat = serialize($param['student_seat']);
                $data_seat3['student_seat']= $student_seat;
                $data_seat3['classes_id']= $enable_class[1];
                $data_seat3['course_id']= $course_id;
                $data_seat3['classroom_id'] =$continue_class3['classroom_id'];
                $data_seat3['student_id']= $student_id;
                $data_seat3['create_time']= time();
            }
            //是否插板过来的学生
            if (!empty($cha_id)) {
                //插板 连报产生的费用
                if ($discount_type == 1) {  //插板和连报一年的
                    //算法 一年的课程价格-一年的课程价格*当前课时+报名费+学杂费
                    $data['amount'] = $year_money - ($year_money / $length) * $progress
                        + $data_class['incidental_price'] + $data_class['signup_price'];

                }
                if ($discount_type == 2 && $course_data['is_year_one']==0) { //插板和连报二年的 且不存在一年优惠价格
                    //算法 一年的原课程价格*2-一年的课程价格*当前课时+报名费+学杂费
                    $data['amount'] = ($course_data['total_price'] *2 - ($course_data['total_price']  / $length) * $progress)
                        + $data_class['incidental_price'] + $data_class['signup_price'];
                }else if($discount_type == 2 && $course_data['is_year_one']==1) {  //插板和连报二年的 且存在一年优惠价格
                    //算法 一年的优惠课程价格*2-一年的课程价格*当前课时+报名费+学杂费
                    $data['amount'] = ($year_one*2 - ($year_one / $length) * $progress)
                        + $data_class['incidental_price'] + $data_class['signup_price'];
                }
                if ($discount_type == 3  && $course_data['is_year_one']==0 && $course_data['is_year_two']==0) {
                    //插板和连报二年的 且不存在一年优惠价格和二年的优惠价格
                    $data['amount'] = ($course_data['total_price'] *3- ($course_data['total_price']  / $length) * $progress)
                        + $data_class['incidental_price'] + $data_class['signup_price'];
                }else if($discount_type == 3  && $course_data['is_year_one']==0 && $course_data['is_year_two']==1)
                {   //插板和连报二年的 且存在一年优惠价格和不存在二年的优惠价格
                    $data['amount'] = ($course_data['total_price'] +$year_two- ($course_data['total_price']  / $length) * $progress)
                        + $data_class['incidental_price'] + $data_class['signup_price'];
                }
                else if($discount_type == 3  && $course_data['is_year_one']==1 && $course_data['is_year_two']==0)
                {    //插板和连报二年的 且不存在一年优惠价格和存在二年的优惠价格
                    $data['amount'] = ($year_one*3- ($year_one/ $length) * $progress)
                        + $data_class['incidental_price'] + $data_class['signup_price'];
                }
                else if($discount_type == 3  && $course_data['is_year_one']==1 && $course_data['is_year_two']==1)
                {   //插板和连报二年的 且存在一年优惠价格和存在二年的优惠价格
                    $data['amount'] = ($year_one+$year_two- ($year_one/ $length) * $progress)
                        + $data_class['incidental_price'] + $data_class['signup_price'];
                }
            }else{ //连报没有插板的情况，可能是1,2，3年连报
                $data['amount'] = $year_money+ $data_class['incidental_price'] + $data_class['signup_price'];
            }
        }else{ //没有连报的情况
            if (!empty($cha_id)) { //没有连报插板，就是一年课程
                $data['amount'] = ($course_data['total_price'] - ($course_data['total_price'] / $length) * $progress)
                    + $data_class['incidental_price'] + $data_class['signup_price'];
            }else{ //正常报一年，没有插板
                $data['amount'] = $data_class['total_price'];
            }
        }
        //牛牛卡的减免方式，根据连报方式
        $award_money = 0;
        $data['niu_card_ids'] = '';
        if (isset($discount_type) && $discount_type == 0) {
            if (isset($param['award_money1'])) { //牛牛卡存在
                foreach ($param['award_money1'] as $k => $v) {
                    if (count($param['award_money1']) == 1) {
                        $data['niu_card_ids'] = $v;
                        $money = $award_model->where('id', $v)->value('award_money');
                        $award_money +=$money;
                    } else {
                        $money = $award_model->where('id', $v)->value('award_money');
                        $award_money += $money;
                        $data['niu_card_ids'] .= $v . ',';
                    }
                }
            }
            if (isset($param['award_money2'])) { //奖学金存在
                foreach ($param['award_money2'] as $k => $v) {
                    if (count($param['award_money2']) == 1) {
                        $data['niu_card_ids'] = $v;
                        $money = $award_model->where('id', $v)->value('award_money');
                        $award_money += $money;
                    } else {
                        $money = $award_model->where('id', $v)->value('award_money');
                        $award_money += $money;
                        $data['niu_card_ids'] .= $v . ',';
                    }
                }
            }
        }

        // 老学员减免报名费
        $data['old_student_discount'] = 0;
        $is_old_student=Db::name('student')->where(['id'=>$student_id])->value('is_old_student'); //看看是不是老学生 报名费
        if ($is_old_student==1) {
            $data['old_student_discount'] = $data_class['signup_price'];
        }
        //助学金的判断是否有而且通过审核
        $help_awrad=$param['help_awrad'];
        $help_awrad_data = Db::name('help_award')->alias('ha')
            ->join('help_award_money h', 'ha.award_id=h.id')
            ->where(['ha.student_id' => $student_id, 'ha.status' => 2,'ha.delete_time'=>0])->value('ha.money');
        if (!empty($help_awrad_data && !empty($help_awrad)) ) {
            $data['help_award'] = $help_awrad_data;
        } else {
            $help_awrad_data = 0;
            $data['help_award'] = 0;
        }
        $data_bill=[]; //bill数据
        if (!empty($param['bill_status'])) {
            $data['bill_status'] = 1;
            $data_bill['payee']=$param['payee'];
            $data_bill['bill_type']=$param['bill_type'];
            $data_bill['recipient']=$param['recipient'];
            $data_bill['phone']=$param['phone'];
            $data_bill['tax_code']=$param['tax_code'];
            $data_bill['address']=$param['address'];
            $data_bill['obtain_type']=$param['obtain_type'];
            $data_bill['create_time']=time();

        }

//        dump($data['amount']);
//        dump( $data_class['incidental_price']);
//        dump( $data_class['signup_price']);
//
//        dump($data);
//        exit();
//        dump($param['award_money2']);
//
//        dump($discount_type);
////

//        $data['discount_amout'] = $data['old_student_discount'] + $award_money + $help_awrad_data + $data['continue_year_money'];
//        $data['pay_amount'] = $data['amount'] - $data['old_student_discount'] - $award_money- $help_awrad_data;


//        dump($data['discount_amout']);
//        dump($data['pay_amount']);
//
//        dump($help_awrad_data);
//        dump($award_money);
//
//
        if(!empty($discount_type))
        {//助学金不能连报、
            $help_awrad_data=0;
        }
        Db::startTrans();
        try {
            //bill发票表
            if (!empty($param['bill_status'])) {
                $bill_id=Db::name('bill')->insertGetId($data_bill);
            }else{
                $bill_id=0;
            }
            //如果是新学员，报名后就是老学员了
            if(empty($is_old_student))
            {
                $is_old_student=Db::name('student')->where(['id'=>$student_id])->update(['is_old_student'=>1]); //看看是不是老学生 报名费
            }

            //order
            $data['parent_id'] = $p_id;
            $data['bill_id'] = $bill_id;
            $data['order_id'] = $order_model->generate_code();
            $data['student_id'] = $student_id;
            $data['class_id']=$class_id;
            $data['class_name']=$class_name;
            $data['discount_amout'] = $data['old_student_discount'] + $award_money + $help_awrad_data ;
//            $data['discount_amout'] = $data['old_student_discount'] + $award_money + $help_awrad_data + $data['continue_year_money'];

            $data['amount']=number_format($data['amount'],2,'.','');

            $data['pay_amount'] = number_format($data['amount'] - $data['old_student_discount'] - $award_money- $help_awrad_data,2,'.','');

         /*   if( $data['pay_amount']<=0)
            {  //剩下余额了
                $data['order_status']=1;
                $data['pay_amount']=0;
                $data['pay_time']=time();
                $data['create_time']=time();
                $data['update_time']=time();
                $balance=$balance-$data['pay_amount'];
                $user_model->where(['id'=>$p_id])->update(['balance'=>$balance]);

            }else{ //大于0说明余额全花掉了
                $balance=0;
                $user_model->where(['id'=>$p_id])->update(['balance'=>$balance]);
            }
        */
            if(!empty($data['discount_amout']))
            {
                $data['discount_amout']=number_format($data['discount_amout'],2,'.','');
            }
            $data['discount_amout']=$data['discount_amout'];


            $data['create_time'] = time();
            $data['cancel_time'] = time() + config('order_expire_time');

            $insert_id = $order_model->insertGetId($data);//订单表
            //牛牛卡使用过后存在表中award_order
            if (isset($param['award_money1'])) {
                $data_model = [];
                foreach ($param['award_money1'] as $k => $v) {
                    $data_model['u_id'] = $p_id;
                    $data_model['award_student_id'] = intval($v);
                    $data_model['order_id'] = $insert_id;
                    $data_model['create_time']=time();
                    Db::name('award_order')->insert($data_model); //如果存在，用牛牛卡就不能再使用了
                }
            }
            if (isset($param['award_money2'])) {
                $data_model = [];
                foreach ($param['award_money2'] as $k => $v) {
                    $data_model['student_id'] = $student_id;
                    $data_model['award_student_id'] = intval($v);
                    $data_model['order_id'] = $insert_id;
                    $data_model['create_time']=time();
                    Db::name('award_order')->insert($data_model); //如果存在，用牛牛卡就不能再使用了
                }
            }
            if($discount_type == 3)
            {
                $class_seat_model->insert($data_seat2);
                $class_student_model->insert($data_student2);
                $class_seat_model->insert($data_seat3);
                $class_student_model->insert($data_student3);
                $count = $class_student_model->where(['class_id' => $enable_class[0]])->count();
                $class_model->where(['id' => $enable_class[0]])->update(['current_num' => $count]);

                $count = $class_student_model->where(['class_id' => $enable_class[1]])->count();
                $class_model->where(['id' => $enable_class[1]])->update(['current_num' => $count]);
            }elseif($discount_type==2)
            {
                $class_seat_model->insert($data_seat2);
                $class_student_model->insert($data_student2);
                $count = $class_student_model->where(['class_id' => $enable_class[0]])->count();
                $class_model->where(['id' => $enable_class[0]])->update(['current_num' => $count]);
            }
            $class_seat_model->insert($data_seat);
            $class_student_model->insert($data_student);
            $count = $class_student_model->where(['class_id' => $class_id])->count();
            $class_model->where(['id' => $class_id])->update(['current_num' => $count]);

            Db::commit();
            return $insert_id;
        } catch (Exception $e) {
            Db::rollback();
            return 0;
        }


    }
    /*
       * 递归一个函数连报,首先判断连报的课程的 is_class enable_class_ids
      */
    public function enable_class($class_id, $data = [])
    {
        $class_data = Db::name('class')->where(['id' => $class_id])->find();
        $is_class = $class_data['is_class'];
        $enable_class = $class_data['enable_class_ids'];
        if (!empty($is_class)) {
            if (!empty($enable_class)) {
                $class_id = intval(explode(',', $enable_class)[0]);
                $data[] = $class_id;
                $data = array_merge($data, $this->enable_class($class_id));
            }else{
                return $data;
            }
        }
        return $data;
    }


}